<?php
/**
 * SBOrderProcessor.php
 * description:
 * Created by www.
 * User: SCF
 * Date: 2018/9/8 15:40
 *
 */

namespace App\Console\Commands\ThirdOrder;

use App\Services\ThirdAPI\GameApiService;
use App\Services\ThirdAPI\SBAPIService;
use App\Services\UserService;
use common\utils\RedisKeys;
use Illuminate\Support\Facades\Redis;


class SBOrderProcessor extends BaseOrderProcessor
{
    protected $signature = self::PREFIX . 'sb';
    protected $description = 'SB体育注单拉取';

    public $sbService;
    public $redis;
    public $cashOut;
    public $lockRedisKeyTime = RedisKeys::SB_LOCK_AUTOFIX_TIME;
    public $lockRedisKeyId = RedisKeys::SB_LOCK_AUTOFIX_ID;
    public $updateRedisKey= RedisKeys::SB_UPDATE_ID;
    public $latestUpdateKeyId;

    public static $OddsTypeEnum = [
        '1' => '马来盘',
        '2' => '香港盘',
        '3' => '欧洲盘',
        '4' => '印度盘',
        '5' => '美国盘'
    ];
    // Status: 注单状态:0=等待；1=接受；2=结算；3=取消；4=拒绝
    // Result: 输赢结果：0=打和；1=全赢；2=全输；3=赢半；4=输半；
    public static $BetStatusEnum = [
        0 => '等待',
        1 => '接受',
        2 => '结算',
        3 => '取消',
        4 => '拒绝',
    ];
    public static $TicketStatusEnum = [
        "half won" => "赢半",
        "half lose" => "输半",
        "won" => "全赢",
        "lose" => "全输",
        "refund" => "退款",
        "draw" => "打和",
        "waiting" => "等待",
        "reject" => "拒绝",
        "void" => "注单作废",
        "running" => "进行中",
    ];

    /**
     * 初始化信息，子类需要重写这个方法
     */
    public function init($argv = null)
    {
        // 必须调用父类init，初始化公共信息
        parent::init();
        // 5.第三方 partner id，名字，对应第三方表id
        $this->partnerName = "SB";
        $this->sbService = new SBAPIService();
        $this->redis = Redis::connection();
        $info = GameApiService::getApiPartnerInfoByName($this->partnerName);
        $this->partnerID = $info['id'];
        $this->orderType = self::ORDER_TYPE_SPORT;
        $this->reportOrderType = self::GAME_TYPE_SPORT;
        $this->userInfos = [];
    }

    /**
     * 向第三方API抓取数据
     */
    public function catchData()
    {
        $lastid = OrderStrategy::getUpdateKeyId($this->lockRedisKeyTime, $this->updateRedisKey,$this->lockRedisKeyId);
        $data = $this->sbService->getBetDetail($lastid);
        if ($data !== false) {
            $this->redis->set(RedisKeys::SB_UPDATE_ID,$data['last_version_key']);
            $this->latestUpdateKeyId = $data['last_version_key'];
            return $data['list'];
        } else {
            return [];
        }
    }

    /**
     * 处理数据
     * 不可以放复杂操作，因为拉取到的每个数据都会经过 load 加载
     */
    public function load($data)
    {
        $this->updateTime = $data['update_time'];
        $this->betTime = $data['bet_time'];
        $this->settleTime = $data['settle_time'];
        $this->reportTime = $data['report_time'];
        $this->betMoney = $data['bet_money'];
        $this->prizeMoney = $data['prize_money'];
        $this->winLossMoney = $data['winloss_money'];
        $this->apiUserName = $data['api_username'];
        $this->contributeMoney = $data['contribute_money']??0;
        $this->bonusMoney = $data['bonus_money']??0;
        $this->validMoney = $data['valid_money'];
        $this->commonStatus = $data['common_status'];
        $this->updateKey = $data['update_key'];
        $this->apiStatus = $data['api_status'];
        $this->gameCode = $data['game_code'];
        $this->gameName = $data['game_name'];
        $this->betContent = $data['bet_content'];
        $this->originData = $data['origin_data'];
        $this->orderNumber = $data["order_number"];
    }
    /**
     * 处理数据，每个子类需要根据第三方的单条数据内容来获取有用的信息
     */
    public function initFromData($data)
    {
    }
    /*
     * 更新redis拉取注单ID
     */
    public function updateFlag($updateKey){
        // 更新 version_key
        $lastid = $this->redis->get(RedisKeys::SB_UPDATE_ID);
        $lastid = $updateKey > $lastid ? $updateKey : $lastid;
        $this->redis->set(RedisKeys::SB_UPDATE_ID,$lastid);
    }
    /**
     * 修复数据内容，每个子类需要实现怎么修复数据内容
     */
    public function fixData($start_date)
    {
        $typeName = "SB";
        echo "Fix {$typeName} report_date" . PHP_EOL;

        $data = Order::where("type_name = '{$typeName}' and created>='{$start_date}'")->get()->toArray();
        echo "get sql date: " . count($data) . PHP_EOL;
        if (count($data) > 0) {
            foreach ($data as $value) {
                $origin = json_decode($value['extra'],true);
                if (!$origin){
                    $value['extra'] = stripslashes($value['extra']);
                    $origin = json_decode($value['extra'],true);
                }
                $validMoney = $value['money'];
                $oddsType = "";
                if ( in_array($origin['ticket_status'], ["Half WON", "Half LOSE", "WON", "LOSE", "DRAW"]) ) {
                    if ($origin['ticket_status'] == "WON"){
                        $betResult2 = 1;
                    }elseif($origin['ticket_status'] == "LOSE"){
                        $betResult2 = 2;
                    } elseif ($origin['ticket_status'] == "Half WON") {
                        $betResult2 = 3;
                    } elseif ($origin['ticket_status'] == "Half LOSE") {
                        $betResult2 = 4;
                    } elseif ($origin['ticket_status'] == "DRAW") {
                        $betResult2 = 0;
                    }
                    //赔率统一
                    if ($origin['odds_type'] == 1){
                        $oddsType = 'MY';
                    }elseif ($origin['odds_type'] == 2){
                        $oddsType = 'HK';
                    }elseif ($origin['odds_type'] == 3){
                        $oddsType = 'EU';
                    }elseif ($origin['odds_type'] == 4){
                        $oddsType = 'ID';
                    }elseif ($origin['odds_type'] == 5){
                        $oddsType = 'US';
                    }

                    //计算有效投注金额
                    if (isset($betResult2)){
                        $validMoney = GameApiService::calcValidBet($oddsType,$origin['odds'],$value['money'],$betResult2);
                    }
                }
                $orderNumber = $value['order_number'];
                $orderModel = Order::where(['order_number' => $orderNumber, 'type_name' => $typeName])->first();
                $orderModel->valid_money = $validMoney;
                $orderModel->save();
            }
        }
        echo "Finish {$typeName} repair!" . PHP_EOL;
    }
}